define(['request', 'hciCore'], function (Request, hciCore) {
    var HCIMultiSelect = function (params) {
        var self = this;
        self.params = $.extend(true, {}, self.defParams, params);
        self.init();
    };
    HCIMultiSelect.prototype.defParams = {
        target: '',//jquery 对象
        attachType: '',// list | tree | grid
        placeholder: '请勾选选择项！',
        width: 160,
        dataAction: "server",
        listParam: {
            selectTextField: '',
            selectValueField: '',
            data: [],
            ajaxParam: {
                url: '',
                data: {},
                success: function (data) {
                    // alert(JSON.stringify(data));
                }
            },
            afterLoadData: function (data) {

            },
            renderData: function (data) {
                return data["result"];
            }
        },
        gridParam: {},
        treeParam: {}
    };
    HCIMultiSelect.prototype.init = function () {
        var self = this;
        var jqTarget = $(self.params.target).addClass("multi-select");
        jqTarget.width(self.params.width);
        var jqInput = $('<input type="text" />').attr({"placeholder": self.params.placeholder}).width(self.params.width - 35);
        var jqDownIcon = $('<div></div>').addClass("multi-arrow-down");
        jqTarget.append(jqInput).append(jqDownIcon);
        var newId = hciCore.newId();
        var id = "multi-select-" + newId;
        var jqMultiSelectList = $("<div  class='multi-list-panel' style='display: none;'></div>").attr({"id": id});
        var jqMultiSelectUl = $("<ul></ul>");
        self["id"] = id;
        self["_input"] = jqInput;
        self["_multiSelectUl"] = jqMultiSelectUl;
        jqMultiSelectList.append(jqMultiSelectUl);
        var getSelectValues = function (jqMultiSelectUl) {
            var valueArray = [];
            var textArray = [];
            $(jqMultiSelectUl).find("li").each(function () {
                if ($(this).find("input[type='checkbox']").prop('checked')) {
                    valueArray.push($(this).find("input").val());
                    textArray.push($(this).find("span").text());
                }
            })
            return {valueArray: valueArray, textArray: textArray};
        };
        var renderData = function (data) {
            data = self.params.listParam["renderData"](data);
            $.each(data, function (index, item) {
                var value = item[self.params.listParam.selectValueField];
                var text = item[self.params.listParam.selectTextField];
                var jqCheckbox = $("<input type='checkbox'/>").attr({value: value});
                var jqText = $("<span></span>").text(text);
                var jqLi = $("<li></li>").append(jqCheckbox).append(jqText);
                jqMultiSelectUl.append(jqLi);
                jqLi.on("click", function () {
                    var resultJSON = {};
                    if ($(this).find("input[type='checkbox']").prop('checked')) {
                        $(this).find("input[type='checkbox']").prop('checked', false);
                        resultJSON = getSelectValues(jqMultiSelectUl);
                    } else {
                        $(this).find("input[type='checkbox']").prop('checked', true);
                        resultJSON = getSelectValues(jqMultiSelectUl);
                    }
                    jqInput.val(resultJSON["textArray"]).attr({title: resultJSON["textArray"]});
                });
            })
        }
        if (self.params.dataAction == "server") {
            var req = new Request(self.params.listParam.ajaxParam["url"]);
            var ajaxParam = $.extend(true, {}, self.params.listParam.ajaxParam);
            delete ajaxParam["url"];
            var callbackObj = $.extend(true, {}, {success: ajaxParam["success"]});
            delete ajaxParam["success"];
            ajaxParam["success"] = function (data) {
                renderData(data);
                if (typeof (callbackObj) == "function") {
                    callbackObj(data);
                }
                if (typeof (self.params.listParam.afterLoadData) == "function") {
                    self.params.listParam.afterLoadData(jqInput, jqMultiSelectUl, data);
                }
            }
            req.get(ajaxParam);
        } else {
            renderData(self.params.listParam.data);
            if (typeof (self.params.listParam.afterLoadData) == "function") {
                self.params.listParam.afterLoadData(jqInput, jqMultiSelectUl, self.params.listParam.data);
            }
        }
        $("body").append(jqMultiSelectList);
        jqTarget.on("click", function () {
            var _this = $(this);
            var popup = new dhtmlXPopup();
            popup.attachObject(id);
            var x = window.dhx4.absLeft(this);
            var y = window.dhx4.absTop(this);
            var w = _this.width();
            var h = _this.height();
            popup.show(x, y, w, h);
        });
    };

    HCIMultiSelect.prototype.getSelectedValue = function () {
        var self = this;
        var valueArray = [];
        self["_multiSelectUl"].find("li").each(function () {
            if ($(this).find("input[type='checkbox']").prop('checked')) {
                valueArray.push($(this).find("input[type='checkbox']").val());
            }
        });
        return valueArray.join(",");
    };
    HCIMultiSelect.prototype.setSelectedValue = function (value) {
        var self = this;
        var valueArray = value.split(",");
        var textArray = [];
        self["_multiSelectUl"].find("li").each(function () {
            var value = $(this).find("input[type='checkbox']").val();
            if (valueArray.indexOf(value) > -1) {
                $(this).find("input[type='checkbox']").prop('checked', true);
                textArray.push($(this).find("span").text());
            }
        })
        self["_input"].val(textArray.join(","));
    }
    return HCIMultiSelect;
})